#!/usr/bin/env /usr/local/python3
# -*- coding: utf-8 -*-

import cv2 as cv
import easyocr
from matplotlib import pyplot as plt

"""
FLANN匹配器只能使用SURF和SIFT算法。

图片与视频对比，找出对应的图片
"""

__author__ = "hubert"


# 采用SIFT算法
def img_sift(img_ex, video_path):
    # rtsp://admin:admin@192.168.2.64:554//Streaming/Channels/1
    cap = cv.VideoCapture(video_path)
    # 灰度
    # img_ex = cv2.imread("/Users/hubert/Downloads/视频测试/example.jpg", 0)

    img_ex = cv.imread(img_ex, 0)

    # 匹配数量
    MIN_MATCH_COUNT = 30

    # 读取视频
    while cap.isOpened():
        retval, image = cap.read()
        if not retval:  # 读完视频后falg返回False
            print("播放完毕，退出")
            break
        print("时间：", cap.get(0))  # cap.get(0) 视频文件的当前位置（播放）以毫秒为单位
        # """
        if retval:
            image = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
            # 只使用SIFT 或 SURF 检测角点 opencv4.4版本以下使用cv2.xfeatures2d.SIFT_create()
            sift = cv.SIFT_create()
            # sift = cv2.xfeatures2d.SURF_create(float(4000))
            kp1, des1 = sift.detectAndCompute(img_ex, None)
            kp2, des2 = sift.detectAndCompute(image, None)

            # 设置FLANN匹配器参数
            # algorithm设置可参考https://docs.opencv.org/3.1.0/dc/d8c/namespacecvflann.html
            indexParams = dict(algorithm=0, trees=5)
            searchParams = dict(checks=50)
            # 定义FLANN匹配器
            flann = cv.FlannBasedMatcher(indexParams,searchParams)
            try:
                # 使用 KNN 算法实现匹配
                matches = flann.knnMatch(des1, des2, k=2)
                # print(matches)
            except Exception as ex:
                print("匹配异常：", str(ex))
                # break


            # 根据matches生成相同长度的matchesMask列表，列表元素为[0,0]
            matchesMask = [[0, 0] for i in range(len(matches))]

            good = []
            # 去除错误匹配
            for i, (m, n) in enumerate(matches):
                if m.distance < 0.7*n.distance:
                    matchesMask[i] = [1, 0]
                    good.append(m)
            if len(good) > MIN_MATCH_COUNT:
                print("已匹配到图片")

            # 将图像显示
            # matchColor是两图的匹配连接线，连接线与matchesMask相关
            # singlePointColor是勾画关键点
            drawParams = dict(matchColor=(0, 255, 0),
                              singlePointColor=(255, 0, 0),
                              matchesMask=matchesMask,
                              flags=0)
            resultImage = cv.drawMatchesKnn(img_ex, kp1, image, kp2, matches, None, **drawParams)

            cv.resize(resultImage, None, fx=0.5, fy=0.5)
            # 显示视频窗
            cv.imshow("Video_Frame", resultImage)
        # """
        if cv.waitKey(1) & 0xFF == ord('q'):
            break
    cv.destroyAllWindows()
    cap.release()


def img_ocr(video_path):
    cap = cv.VideoCapture(video_path)
    # 读取视频
    while cap.isOpened():
        retval, image = cap.read()
        if not retval:  # 读完视频后falg返回False
            print("播放完毕，退出")
            break
        print("时间：", cap.get(0))  # cap.get(0) 视频文件的当前位置（播放）以毫秒为单位
        # """
        if retval:
            reader = easyocr.Reader(['ch_sim','en'], True)
            # 比较消耗性能
            result = reader.readtext(image)
            for i in result:
                word = i[1]
                # print(word)
            print(result)
        if cv.waitKey(1) & 0xFF == ord('q'):
            break
    cv.destroyAllWindows()
    cap.release()


#
if __name__ == '__main__':
    img_ex = "/Users/hubert/Downloads/视频测试/example.jpg"
    img_ex2 = "/Users/hubert/Downloads/视频测试/example3.jpg"
    video_path = "/Users/hubert/Downloads/视频测试/part1.ts"
    video_path2 = "/Users/hubert/Downloads/视频测试/part3.ts"

    video_path3 = "/Users/hubert/Downloads/视频测试/6F5C899975164C19B602A8A992FA3169.ts"

    # sift
    img_sift(img_ex, video_path)

    # img_ocr(video_path2)






